//
//  LSZAudioPlaybackInterfaceVC.m
//  PartyClassCloud
//
//  Created by 梁素珍 on 2018/9/2.
//  Copyright © 2018年 九酷. All rights reserved.
//

#import "LSZAudioPlaybackInterfaceVC.h"


@interface LSZAudioPlaybackInterfaceVC ()<UINavigationControllerDelegate,UIGestureRecognizerDelegate>
{
    NSInteger valueSCM;//记录拖拽的值
    UILabel * minLabel;
    UILabel * maxLabel;
    CGFloat totalTime;
}
@property(nonatomic,assign) NSInteger totalValuer;//学习时间
@property(nonatomic,strong) NSTimer * timer;//计时器

@property(nonatomic,strong) UIButton * butPlayerOrSuspended;//暂停或播放
@property(nonatomic,strong) UIImageView * imageViewCover;
@property(nonatomic,strong) UILabel * labelTitle;
@property(nonatomic,strong) UILabel * labelControl;
@property(nonatomic,strong) AVPlayer * audioPlayer;
@property(nonatomic,strong) AVPlayerItem * songItem;

@property(nonatomic,assign) NSInteger isStates;//1播放  2暂停

@property (nonatomic,strong) id playerObserve;
@property (nonatomic,strong) id playerTimeObserver;

@property (nonatomic,assign) CGFloat duration;

@property (strong,nonatomic) LSZUISlider       * mScrubber;     //播放进度
@property (strong,nonatomic) UIProgressView *cacheProgressV;//缓冲进度
@property (nonatomic,strong)NSDateFormatter *dateFormatter;
@property (nonatomic,assign)BOOL isDragingSlider;//是否点击了按钮的响应事件
@property (nonatomic,assign)BOOL statesPlayer;//yes播放  No暂停

@property(nonatomic,strong) NSString * paperId;//记录播放的ID
@end

@implementation LSZAudioPlaybackInterfaceVC
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.delegate = self;
//    // 开始接受远程控制
//    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//    [self becomeFirstResponder];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    __weak typeof(self) weakSelf = self;
    if (weakSelf.statesPlayer == YES) {
        [weakSelf.audioPlayer pause];
        [weakSelf suspendedPlayer];
    }
    weakSelf.statesPlayer = YES;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [weakSelf.audioPlayer replaceCurrentItemWithPlayerItem:nil];
    [weakSelf.timer invalidate];
    weakSelf.timer = nil;
}
/*
// 重写父类成为响应者方法
- (BOOL)canBecomeFirstResponder {
    return YES;
}
//重写父类方法，接受外部事件的处理
- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        
        switch (receivedEvent.subtype) { // 得到事件类型
                
            case UIEventSubtypeRemoteControlTogglePlayPause: // 暂停 ios6
                [self actionStopButton:self.musicViewNew.stopButton]; // 调用你所在项目的暂停按钮的响应方法 下面的也是如此
                break;
                
            case UIEventSubtypeRemoteControlPreviousTrack:  // 上一首
                [self actionUpButton:self.musicViewNew.upMusicButton];
                break;
                
            case UIEventSubtypeRemoteControlNextTrack: // 下一首
                [self actionDownButton:self.musicViewNew.downMusicButton];
                break;
                
            case UIEventSubtypeRemoteControlPlay: //播放
                [self actionStopButton:self.musicViewNew.stopButton];
                break;
                
            case UIEventSubtypeRemoteControlPause: // 暂停 ios7
                [self actionStopButton:self.musicViewNew.stopButton];
                break;
                
            default:
                break;
        }
    }
}
*/
-(void)dealloc{
    __weak typeof(self) weakSelf = self;
    [weakSelf.audioPlayer pause];
    weakSelf.statesPlayer = YES;
    [weakSelf.audioPlayer removeTimeObserver:_playerObserve];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [weakSelf.songItem removeObserver:self forKeyPath:@"status"];
    [weakSelf.songItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
//    [weakSelf.songItem removeObserver:self forKeyPath:@"status"];
    //choosePlayer
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"choosePlayer"];
    weakSelf.songItem=nil;
    weakSelf.audioPlayer=nil;
    [weakSelf.audioPlayer replaceCurrentItemWithPlayerItem:nil];
    [weakSelf.playerObserve removeFromSuperlayer];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    __weak typeof(self) weakSelf = self;
    weakSelf.statesPlayer = NO;
    weakSelf.view.backgroundColor = RGBColor(255, 201, 202);
    [weakSelf setAudio];
    valueSCM = 0;
    UIButton * butReturn = [[UIButton alloc]init];
    butReturn.frame = CGRectMake(20, NAVIGATION_BAR_HEIGHT-40, 50, 40);
    [butReturn setImage:[UIImage imageNamed:@"back_green"] forState:UIControlStateNormal];
    [butReturn addTarget:self action:@selector(clickButReturn) forControlEvents:UIControlEventTouchUpInside];
    [weakSelf.view addSubview:butReturn];
    
    UIButton * butList = [[UIButton alloc]init];
    butList.frame = CGRectMake(ScreenWidth-16*2-10, NAVIGATION_BAR_HEIGHT-40, 16*2, 12*2);
    [butList setImage:[UIImage imageNamed:@"播放列表"] forState:UIControlStateNormal];
    [butList addTarget:self action:@selector(clickPlayList) forControlEvents:UIControlEventTouchUpInside];
     [weakSelf.view addSubview:butList];
    
    [weakSelf setOtherUI];
    [weakSelf AddObserver];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.songItem];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickChoose:) name:@"choosePlayer" object:nil];
    [weakSelf addProgressObservervc];
    
    self.totalValuer = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(clickTimer) userInfo:nil repeats:YES];
}
#pragma mark - 统计在线时长
-(void)clickTimer
{
    self.totalValuer = self.totalValuer+1;
    NSLog(@"统计时间>>>>>>>>>>%ld",(long)self.totalValuer);
    if(self.totalValuer == 90){
        
        self.totalValuer = 0;
        [LSZRequestData WatchAudioAndVideoFinished:@"90" paperId:self.paperId :^(BOOL isOk, NSString * str, NSString * string) {
            
        }];
    }
}
#pragma mark - 暂停播放
-(void)suspendedPlayer
{
    [self.timer setFireDate:[NSDate distantFuture]];
}
#pragma mark - 继续播放
-(void)continueToPlayer
{
    [self.timer setFireDate:[NSDate distantPast]];
}
#pragma mark - KVO 观察播放进度
- (CMTime)playerItemDuration{
    AVPlayerItem *playerItem = self.songItem;
    if (playerItem.status == AVPlayerItemStatusReadyToPlay){
        return([playerItem duration]);
    }
    return(kCMTimeInvalid);
}
-(void)addProgressObservervc
{
    __weak __typeof(self) weakself = self;
    weakself.playerTimeObserver = [weakself.audioPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        CMTime playerDuration = [weakself playerItemDuration];
        if (CMTIME_IS_INVALID(playerDuration)){
            weakself.mScrubber.minimumValue = 0.0;
            return;
        }
        float minValue = [weakself.mScrubber minimumValue];
        float maxValue = [weakself.mScrubber maximumValue];
//        NSLog(@"哈哈哈%lld>>>>>>>>>>>>%d",weakself.songItem.currentTime.value,self.songItem.currentTime.timescale);
        CGFloat  nowTime = weakself.songItem.currentTime.value/weakself.songItem.currentTime.timescale;
        weakself.mScrubber.value =(CGFloat)nowTime/totalTime;

//        NSLog(@"%.2f******************nowTime",nowTime);
        minLabel.text = [weakself convertTime:nowTime];
        maxLabel.text = [weakself convertTime:totalTime];
        if (weakself.isDragingSlider==YES) {//拖拽slider中，不更新slider的值
            NSLog(@"拖拽slider中");
        }else if(weakself.isDragingSlider==NO){
//            NSLog(@"现在闲杂>>>>%.2f",nowTime);
            CGFloat curretValue = (maxValue - minValue) * nowTime / self->totalTime + minValue;
            //            NSLog(@"%f>>>>curretValue",curretValue);
            if (self->valueSCM== 0) {
                [weakself.mScrubber setValue:(maxValue - minValue) * nowTime / self->totalTime + minValue];
            }else{
                if (self->valueSCM == curretValue) {
                    [weakself.mScrubber setValue:(maxValue - minValue) * nowTime / totalTime + minValue];
                    self->valueSCM = 0;
                }
            }
        }
        
    }];
}
- (NSString *)convertTime:(float)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    __weak typeof(self) weakSelf = self;
    if (second/3600 >= 1) {
        [[weakSelf dateFormatter] setDateFormat:@"HH:mm:ss"];
    } else {
        [[weakSelf dateFormatter] setDateFormat:@"mm:ss"];
    }
    return [[weakSelf dateFormatter] stringFromDate:d];
}
- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        _dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
    }
    return _dateFormatter;
}
#pragma mark - 自动播放下一首
- (void)playbackFinished:(NSNotification *)notice {
    __weak typeof(self) weakSelf = self;
    [weakSelf clickNext];
}
#pragma mark - 添加观察者
-(void)AddObserver
{
    __weak typeof(self) weakSelf = self;
    id timeObserve = [self.audioPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current = CMTimeGetSeconds(time);
        float total = CMTimeGetSeconds(weakSelf.songItem.duration);
        if (current) {
            NSLog(@"%@>>>>>%@>>>>>>>11111",[NSString stringWithFormat:@"%.f",current],[NSString stringWithFormat:@"%.2f",total]);
//            weakSelf.mScrubber.p = current / total;
//            weakSelf.playTime = [NSString stringWithFormat:@"%.f",current];
//            weakSelf.playDuration = [NSString stringWithFormat:@"%.2f",total];
        }
    }];
}
-(void)relodLabel
{
    __weak typeof(self) weakSelf = self;
    CGFloat height = [LSZSpecialPackaging getHeightOfText:self.labelTitle.frame.size.width height:ScreenHeight font:18 :weakSelf.labelTitle.text];
    CGRect rect = weakSelf.labelTitle.frame;
    rect.size.height = height;
    weakSelf.labelTitle.frame = rect;
    
    CGFloat heightControl = [LSZSpecialPackaging getHeightOfText:weakSelf.labelControl.frame.size.width height:ScreenHeight font:16 :weakSelf.labelControl.text];
    CGRect rectControl = weakSelf.labelControl.frame;
    rectControl.size.height = heightControl;
    weakSelf.labelControl.frame = rectControl;
}
-(void)setOtherUI
{
    __weak typeof(self) weakSelf = self;
    LSZTertiaryInterfaceMg * mg = nil;
    mg = weakSelf.mutArrayData[weakSelf.numberRow];
    weakSelf.paperId = mg.id_id;
    weakSelf.imageViewCover = [[UIImageView alloc]init];
    weakSelf.imageViewCover.frame = CGRectMake((ScreenWidth-100)/2, NAVIGATION_BAR_HEIGHT, 100, 100);
    [weakSelf.imageViewCover.layer setMasksToBounds:YES];
    [weakSelf.imageViewCover.layer setCornerRadius:weakSelf.imageViewCover.frame.size.height/2];
    [weakSelf.imageViewCover sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",URLTotal,mg.coverUrl]] placeholderImage:[UIImage imageNamed:@"默认"]];
    [weakSelf.view addSubview:weakSelf.imageViewCover];
    weakSelf.labelTitle = [[UILabel alloc]init];
    weakSelf.labelTitle.numberOfLines = 0;
    weakSelf.labelTitle.frame = CGRectMake(30, CGRectGetMaxY(weakSelf.imageViewCover.frame)+30, ScreenWidth-60, 40);
    weakSelf.labelTitle.textColor = [UIColor whiteColor];
    weakSelf.labelTitle.font = FONT_(18);
    weakSelf.labelTitle.text = mg.name;
    weakSelf.labelTitle.textAlignment = NSTextAlignmentCenter;
    [weakSelf.view addSubview:weakSelf.labelTitle];

    weakSelf.labelControl = [[UILabel alloc]init];
    weakSelf.labelControl.frame = CGRectMake(30, CGRectGetMaxY(weakSelf.labelTitle.frame)+15, ScreenWidth-60, 100);
    weakSelf.labelControl.font = FONT_(16);
    weakSelf.labelControl.numberOfLines = 0;
    weakSelf.labelControl.textAlignment = NSTextAlignmentCenter;
    weakSelf.labelControl.textColor = [UIColor whiteColor];
    weakSelf.labelControl.text = mg.summary;
    [weakSelf.view addSubview:weakSelf.labelControl];
    [weakSelf relodLabel];//布局

    [weakSelf setChooseBut];
    weakSelf.isStates = 1;//播放
}
-(void)setChooseBut
{
    __weak typeof(self) weakSelf = self;
    weakSelf.butPlayerOrSuspended = [[UIButton alloc]init];
    weakSelf.butPlayerOrSuspended.frame = CGRectMake((ScreenWidth-70)/2, ScreenHeight-HOME_INDICATOR_HEIGHT-100, 70, 70);
    [weakSelf.butPlayerOrSuspended setImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
    [weakSelf.butPlayerOrSuspended addTarget:self action:@selector(clickPlayerOrSuspended) forControlEvents:UIControlEventTouchUpInside];
    [weakSelf.view addSubview:weakSelf.butPlayerOrSuspended];
    
    UIButton * butLast = [[UIButton alloc]init];
    butLast.frame = CGRectMake(CGRectGetMinX(weakSelf.butPlayerOrSuspended.frame)-100, ScreenHeight-HOME_INDICATOR_HEIGHT-100, 70, 70);
    [butLast setImage:[UIImage imageNamed:@"上一首"] forState:UIControlStateNormal];
    [butLast addTarget:self action:@selector(clickLast) forControlEvents:UIControlEventTouchUpInside];
    [weakSelf.view addSubview:butLast];
    
    UIButton * butNext = [[UIButton alloc]init];
    butNext.frame = CGRectMake(CGRectGetMaxX(weakSelf.butPlayerOrSuspended.frame)+30, ScreenHeight-HOME_INDICATOR_HEIGHT-100, 70, 70);
    [butNext setImage:[UIImage imageNamed:@"下一首"] forState:UIControlStateNormal];
    [butNext addTarget:self action:@selector(clickNext) forControlEvents:UIControlEventTouchUpInside];
    [weakSelf.view addSubview:butNext];
    
    minLabel = [[UILabel alloc]init];
    minLabel.frame = CGRectMake(5, CGRectGetMinY(weakSelf.butPlayerOrSuspended.frame)-60, 50, 40);
    minLabel.textColor = titleColorLSZ;
    minLabel.font = FONT_(13);
    minLabel.text = @"0:00";
    [weakSelf.view addSubview:minLabel];
    
     weakSelf.mScrubber = [[LSZUISlider alloc]initWithFrame:CGRectMake(2+CGRectGetMaxX(minLabel.frame), CGRectGetMinY(self.butPlayerOrSuspended.frame)-60, ScreenWidth-20-minLabel.frame.size.width*2, 40)];
     weakSelf.mScrubber.minimumValue = 0.0;
     weakSelf.mScrubber.maximumValue = 1.0;
     weakSelf.mScrubber.value = 0.0;
    [weakSelf.mScrubber setContinuous:YES];
    weakSelf.mScrubber.maximumValueImage = [UIImage imageNamed:@"001.jpeg"];
    weakSelf.mScrubber.minimumTrackTintColor = themeColor;
    weakSelf.mScrubber.maximumTrackTintColor = RGBColor(244, 244, 244);
    weakSelf.mScrubber.thumbTintColor = RGBColor(255, 78, 0);
    [weakSelf.mScrubber addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [weakSelf.mScrubber addTarget:self action:@selector(updateProgress:) forControlEvents:UIControlEventTouchUpInside];
    [weakSelf.view addSubview:weakSelf.mScrubber];
    //给进度条添加单击手势
    UITapGestureRecognizer * tapClickmScrubber = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionTapGesture:)];
    tapClickmScrubber.delegate = self;
    [weakSelf.mScrubber addGestureRecognizer:tapClickmScrubber];
    

    
    maxLabel = [[UILabel alloc]init];
    maxLabel.frame = CGRectMake(CGRectGetMaxX(weakSelf.mScrubber.frame), CGRectGetMinY(weakSelf.butPlayerOrSuspended.frame)-60, 50, 40);
    maxLabel.textColor = titleColorLSZ;
    maxLabel.font = FONT_(13);
    maxLabel.text = @"0:00";
    [weakSelf.view addSubview:maxLabel];
}
#pragma mark - 拖动
-(void)sliderValueChanged:(UISlider *)slider
{
    __weak typeof(self) weakSelf = self;
    weakSelf.isDragingSlider = YES;
    weakSelf.mScrubber.value = slider.value;
    valueSCM = slider.value;
}
#pragma mark - 播放进度  点击
- (void)updateProgress:(UISlider *)slider{
    __weak typeof(self) weakSelf = self;
    weakSelf.isDragingSlider = NO;
    [weakSelf.audioPlayer seekToTime:CMTimeMakeWithSeconds(slider.value, weakSelf.songItem.currentTime.timescale)];
    weakSelf.mScrubber.value = slider.value;
    valueSCM = slider.value;
    
    // 拖动改变视频播放进度
    if (weakSelf.audioPlayer.status == AVPlayerItemStatusReadyToPlay) {
        // 总秒数
        CGFloat total = (CGFloat)weakSelf.songItem.duration.value / weakSelf.songItem.duration.timescale;
        // 已经拖动到了现在的秒数了。
        NSInteger dragedSeconds = floorf(total * slider.value);
        //转换成CMTime才能给player来控制播放进度---这个类用来控制时间的。
        CMTime dragedCMTime = CMTimeMake(dragedSeconds, 1);
        [weakSelf.audioPlayer pause];
        weakSelf.statesPlayer = NO;
        [weakSelf suspendedPlayer];
        [weakSelf.audioPlayer seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
            if (weakSelf.statesPlayer == NO) {
                [weakSelf.audioPlayer play];
                weakSelf.statesPlayer = YES;
                [weakSelf continueToPlayer];
            }
        }];
    }
}
- (void)actionTapGesture:(UITapGestureRecognizer *)sender {
    __weak typeof(self) weakSelf = self;
    CGPoint touchLocation = [sender locationInView:weakSelf.mScrubber];
    CGFloat value = (weakSelf.mScrubber.maximumValue - weakSelf.mScrubber.minimumValue) * (touchLocation.x/weakSelf.mScrubber.frame.size.width);
    [weakSelf.mScrubber setValue:value animated:YES];
    
    [weakSelf.audioPlayer seekToTime:CMTimeMakeWithSeconds(weakSelf.mScrubber.value, weakSelf.songItem.currentTime.timescale)];
    if (weakSelf.audioPlayer.rate != 1.f) {
        if ([weakSelf currentTime] == [weakSelf duration]){
            [weakSelf setCurrentTime:0.f];
//            self.butChange.selected = NO;
            NSLog(@"nononononono");
        }else{
            NSLog(@"yesyesyesyes");
        }
        //        [self.playerVideo play];
    }
    NSLog(@"拖拽拖拽value>>>>>>>>>>>%f",value);
}
///获取视频当前播放的时间
- (double)currentTime{
    __weak typeof(self) weakSelf = self;
    if (weakSelf.audioPlayer) {
        return CMTimeGetSeconds([weakSelf.audioPlayer currentTime]);
    }else{
        return 0.0;
    }
}
- (void)setCurrentTime:(double)time{
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.audioPlayer seekToTime:CMTimeMakeWithSeconds(time, weakSelf.songItem.currentTime.timescale)];
    });
}
#pragma mark - 暂停和播放
-(void)clickPlayerOrSuspended
{
    __weak typeof(self) weakSelf = self;
    if(weakSelf.isStates == 1 ){
        weakSelf.isStates = 2;
        [weakSelf.butPlayerOrSuspended setImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
        [weakSelf.audioPlayer pause];
        weakSelf.statesPlayer = NO;
        [weakSelf suspendedPlayer];
    }else{
        [weakSelf.butPlayerOrSuspended setImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
        [weakSelf.audioPlayer play];
        weakSelf.statesPlayer = YES;
        weakSelf.isStates = 1;
        [weakSelf continueToPlayer];
    }
}
#pragma mark - 上一个
-(void)clickLast
{
    __weak typeof(self) weakSelf = self;
    if (weakSelf.numberRow == 0) {
        [weakSelf initWithtring:@"这已经是第一首了!"];
        return;
    }
    maxLabel.text = @"0:00";
    minLabel.text = @"0:00";
    weakSelf.totalValuer = 0;
    weakSelf.numberRow = self.numberRow - 1;
    LSZTertiaryInterfaceMg * mg = nil;
    mg = weakSelf.mutArrayData[weakSelf.numberRow];
    [weakSelf setUpdateTheData:mg];
}
#pragma mark - 下一个
-(void)clickNext
{
    __weak typeof(self) weakSelf = self;
    if (weakSelf.numberRow == weakSelf.mutArrayData.count-1) {
        [weakSelf initWithtring:@"这已经是最后一首了!"];
        return;
    }
    weakSelf.totalValuer = 0;
    maxLabel.text = @"0:00";
    minLabel.text = @"0:00";
    weakSelf.numberRow = weakSelf.numberRow +1;
    LSZTertiaryInterfaceMg * mg = nil;
    mg = weakSelf.mutArrayData[weakSelf.numberRow];
    [weakSelf setUpdateTheData:mg];
}
#pragma mark - 切换音频
-(void)clickChoose:(NSNotification *)notification
{
    __weak typeof(self) weakSelf = self;
    NSInteger row = [notification.userInfo[@"row"] integerValue];
    if(row == weakSelf.numberRow){
        [weakSelf initWithtring:@"该音频正在播放中!"];
        return;
    }
    weakSelf.numberRow = row;
    maxLabel.text = @"0:00";
    minLabel.text = @"0:00";
    LSZTertiaryInterfaceMg * mg = nil;
    mg = weakSelf.mutArrayData[weakSelf.numberRow];
    [weakSelf setUpdateTheData:mg];
}
-(void)setUpdateTheData :(LSZTertiaryInterfaceMg*)mg
{
    __weak typeof(self) weakSelf = self;
    weakSelf.paperId = mg.id_id;
    [weakSelf.audioPlayer pause];
    weakSelf.statesPlayer = NO;
//    weakSelf.songItem = nil;
    [weakSelf suspendedPlayer];
    [weakSelf.songItem removeObserver:self forKeyPath:@"status" context:nil];
    [weakSelf.songItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    [weakSelf.audioPlayer replaceCurrentItemWithPlayerItem:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    
    weakSelf.songItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:mg.contentUrl]];
    [weakSelf.audioPlayer replaceCurrentItemWithPlayerItem:weakSelf.songItem];
    if(weakSelf.audioPlayer.status ){
        
    }
    if (weakSelf.statesPlayer == NO) {
        [weakSelf.audioPlayer play];
        weakSelf.statesPlayer = YES;
        [weakSelf continueToPlayer];
    }
    weakSelf.labelTitle.text = mg.name;
    weakSelf.labelControl.text = mg.summary;
    [weakSelf relodLabel];//布局
    [weakSelf.imageViewCover sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",URLTotal,mg.coverUrl]] placeholderImage:[UIImage imageNamed:@"默认"]];
    
 
    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:weakSelf.audioPlayer];
    layer.frame = weakSelf.view.bounds;
    layer.videoGravity = AVLayerVideoGravityResizeAspect;
    [weakSelf.view.layer addSublayer:layer];
    //这里监听avplayer是否播放完成，完成调用playDidFinished:
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playDidFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:weakSelf.songItem];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickChoose:) name:@"choosePlayer" object:nil];

    //对于1分钟以内的视频就每1/30秒刷新一次页面，大于1分钟的每秒一次就行
    CMTime interval = _duration > 60 ? CMTimeMake(1, 1) : CMTimeMake(1, 30);
    //这个方法就是每隔多久调用一次block，函数返回的id类型的对象在不使用时用-removeTimeObserver:释放，官方api是这样说的
    _playerObserve = [weakSelf.audioPlayer addPeriodicTimeObserverForInterval:interval queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        if(!weakSelf.mScrubber){
            CGFloat currentTime = CMTimeGetSeconds(time);
//            NSString *timeText = [NSString stringWithFormat:@"%@/%@", [weakSelf convert:currentTime], [weakSelf convert:weakSelf.duration]];
//            weakSelf.bottomView.timeLabel.text = timeText;
//
//            weakSelf.bottomView.mScrubber.value = currentTime / weakSelf.duration;
        }
    }];
    [weakSelf addKVO];
    
    

}
- (void)playDidFinished:(NSNotification *)notification{
//    [_bottomView.playButton setBackgroundImage:[UIImage imageNamed:@"btn_video_play"] forState:UIControlStateNormal];
    __weak typeof(self) weakSelf = self;
    [weakSelf.audioPlayer pause];
    weakSelf.statesPlayer = NO;
//    _playerStatu = End;
    [weakSelf suspendedPlayer];
}
-(void)setAudio
{
    __weak typeof(self) weakSelf = self;
    LSZTertiaryInterfaceMg * mg = nil;
    mg = weakSelf.mutArrayData[weakSelf.numberRow];
    weakSelf.paperId = mg.id_id;
    weakSelf.songItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:mg.contentUrl]];
    [weakSelf.audioPlayer replaceCurrentItemWithPlayerItem:weakSelf.songItem];
    if (weakSelf.statesPlayer == NO) {
        [weakSelf.audioPlayer play];
        weakSelf.statesPlayer = YES;
        [weakSelf continueToPlayer];
    }
    [weakSelf addKVO];
}
-(void)addKVO
{
    __weak typeof(self) weakSelf = self;
    [weakSelf.songItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [weakSelf.songItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}
//然后可以在KVO方法中获取其status的改变
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context {
    __weak typeof(self) weakSelf = self;
    AVPlayerItem *playerItems = (AVPlayerItem *)object;
    totalTime = playerItems.duration.value / playerItems.duration.timescale; //视频总时间
    if ([keyPath isEqualToString:@"status"]) {
        switch (weakSelf.audioPlayer.status) {
            case AVPlayerStatusUnknown:
                [weakSelf initWithtring:@"KVO：未知状态，此时不能播放"];
                if (weakSelf.statesPlayer == YES) {
                    [weakSelf.audioPlayer pause];
                    weakSelf.statesPlayer = NO;
                    [weakSelf suspendedPlayer];
                }
                break;
            case AVPlayerStatusReadyToPlay:
//                self.status = SUPlayStatusReadyToPlay;
                if (weakSelf.statesPlayer == NO) {
                    [weakSelf.audioPlayer play];
                    weakSelf.statesPlayer = YES;
                    [weakSelf continueToPlayer];
                }//                NSLog(@"准备完毕，可以播放");
//                BASE_INFO_FUN(@"KVO：准备完毕，可以播放");
                break;
            case AVPlayerStatusFailed:
                [weakSelf initWithtring:@"资源播放失败!"];
                if (weakSelf.statesPlayer == YES) {
                    [weakSelf.audioPlayer pause];//播放失败
                    weakSelf.statesPlayer = NO;
                    [weakSelf suspendedPlayer];
                }
                break;
            default:
                break;
        }
    }
    AVPlayerItem * songItem = object;
    if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSArray * array = songItem.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue]; //本次缓冲的时间范围
        NSTimeInterval totalBuffer = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration); //缓冲总长度
//        NSLog(@"共缓冲%.2f",totalBuffer);
    }
}
- (AVPlayer *)audioPlayer
{
    if (!_audioPlayer) {
        __weak typeof(self) weakSelf = self;
        LSZTertiaryInterfaceMg * mg = nil;
        mg = weakSelf.mutArrayData[weakSelf.numberRow];
        weakSelf.paperId = mg.id_id;
        _songItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:mg.contentUrl]];
        _audioPlayer = [[AVPlayer alloc] initWithPlayerItem:_songItem];
        if([[UIDevice currentDevice] systemVersion].intValue>=10){
            //      增加下面这行可以解决ios10兼容性问题了
            if (@available(iOS 10.0, *)) {
                _audioPlayer.automaticallyWaitsToMinimizeStalling = NO;
            } else {
                // Fallback on earlier versions
            }
        }
    }
    return _audioPlayer;
}
#pragma mark - 点击播放列表
-(void)clickPlayList
{
    LSZAudioPlaylist * list = [[LSZAudioPlaylist alloc]init];
    [list show];
    [list initWithAudioPlaylist:self.mutArrayData];
}
-(void)clickButReturn
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)navigationController:(UINavigationController*)navigationController willShowViewController:(UIViewController*)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}
@end
